package com.nmn.spinningwheel;

import java.util.Random;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.androidquery.callback.ImageOptions;
import com.nmn.spinningwheel.model.Events.OnGetViewSizeDoneEvent;
import com.nmn.spinningwheel.util.CommonUtil;
import com.nmn.spinningwheel.util.CommonUtil.REWARDs;

import de.greenrobot.event.EventBus;
public class SpinScreen extends Activity {
	
	private static Bitmap imageOriginal, imageScaled;
	private static Matrix matrix;
	private AQuery aQuery;
	private ImageView myWheel;
	private int circleHeight, circleWidth;
	Handler handler;
	private boolean allowSpinning=false;
	private boolean isSpinning=false;
	private AlertDialog dialog;
	private boolean adjusted=false;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_spin);
        handler=new Handler();
        aQuery = new AQuery(this);
        if (matrix == null) {
        	matrix = new Matrix();
        } else {
        	matrix.reset();
        }
        if (imageOriginal == null) {
        	imageOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.cycle);
        }
        myWheel = (ImageView) findViewById(R.id.myWheel);
        myWheel.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
			@Override
			public void onGlobalLayout() {
        		if (circleHeight == 0 || circleWidth == 0) {
        			circleHeight = myWheel.getHeight();
        			circleWidth = myWheel.getWidth();
					Matrix resize = new Matrix();
					resize.postScale((float)Math.min(circleWidth, circleHeight) / (float)imageOriginal.getWidth(), (float)Math.min(circleWidth, circleHeight) / (float)imageOriginal.getHeight());
					imageScaled = Bitmap.createBitmap(imageOriginal, 0, 0, imageOriginal.getWidth(), imageOriginal.getHeight(), resize, false);
					Log.e("scaled wheel width","wheel width:"+imageScaled.getWidth()+"wheel height:"+imageScaled.getHeight());
					float translateX = circleWidth / 2 - imageScaled.getWidth() / 2;
					float translateY = circleHeight / 2 - imageScaled.getHeight() / 2;
					matrix.postTranslate(translateX, translateY);
					myWheel.setImageBitmap(imageScaled);
					myWheel.setImageMatrix(matrix);
        		}
        		if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
        			myWheel.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        		   else
        			   myWheel.getViewTreeObserver().removeGlobalOnLayoutListener(this);
			}
		});
        myWheel.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
        int widht = myWheel.getMeasuredWidth();
//        ImageView indicator=(ImageView) findViewById(R.id.indicator);
        LinearLayout.LayoutParams rlParams = (LinearLayout.LayoutParams)myWheel.getLayoutParams();
        rlParams.setMargins(0, 0, -widht/2, 0);
        Log.e("width","width: "+widht);
        myWheel.setLayoutParams(rlParams);
//        RelativeLayout.LayoutParams rlParams2 = (RelativeLayout.LayoutParams)indicator.getLayoutParams();
//        rlParams2.setMargins(0, 0, -widht/2, 0);
//        indicator.setLayoutParams(rlParams2);
        aQuery.id(R.id.greenSpin).clicked(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!isSpinning){
					reward=REWARDs.YELLOW_TYM;
					spinType=R.drawable.green_tym;
					rewardImage=R.drawable.reward_yellow_tym;
					if(CommonUtil.checkShowConfirmSpin(SpinScreen.this)){
						showConfirmSpin();
					}else{
						spin();
					}
					
				}
			}
		});
        aQuery.id(R.id.purpleSpin).clicked(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(!isSpinning){
					reward=REWARDs.PURPLE_TYM;
					spinType=R.drawable.purple_tym;
					rewardImage=R.drawable.reward_purple_tym;
					if(CommonUtil.checkShowConfirmSpin(SpinScreen.this)){
						showConfirmSpin();
					}else{
						spin();
					}
				}
			}
		});
        aQuery.id(R.id.freeSpin).clicked(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(!isSpinning){
					reward=REWARDs.TURN;
					spinType=0;
					rewardImage=0;
					spin();
				}
			}
		});
//        spin();
        aQuery.id(R.id.closeSpin).clicked(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
        Log.e("OnCreated","OnCreated");
    }
	private boolean reset=true;
	private int spinType=0;
	private void spin() {
		velocity=1500;
		totalDegress=0.0f;
		isSpinning=true;
		adjusted=false;
		if(!reset){
			rotateTheWheel(360-previousAngle);
			reset=true;
		}
		startTime=System.currentTimeMillis();
        handler.post(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				long currentTime=System.currentTimeMillis();
				
				if(currentTime<=startTime+3000){
					rotateTheWheel(150);
					totalDegress+=(150);
//					Log.e("velocity","velocity: "+150+", degree: "+150+", totalDegres: "+totalDegress);
					myWheel.post(this);
				}
				else{
					if(!adjusted){
						adjusted=true;
						int offset=(int) (totalDegress%360);
//						Log.e("offset","offset:"+offset);
						float newAngle = 41+getAngle();//+(previousReward==null?0.0f:(360-CommonUtil.getAngle(previousReward)));
//						Log.e("offset","offset-newAngle:"+newAngle);
//						Log.e("offset","offset-previousAngle:"+previousAngle);
//						Log.e("offset","offset-Angle affter all:"+(360-((360-offset+newAngle)%360)));
						rotateTheWheel(360-offset+newAngle);
						previousAngle=(newAngle-41)%360;
						totalDegress=0;
						myWheel.post(this);
						return;
					}
					//end the spinning
					if(Math.abs(velocity)>5){
						rotateTheWheel(velocity/75);
//						Log.e("velocity","velocity: "+velocity+", degree: "+(Math.abs(velocity)/75)+", totalDegres: "+totalDegress);totalDegress+=(Math.abs(velocity)/75);
						velocity/=1.0666F;
						myWheel.post(this);
					}else{
						reset=false;
						isSpinning=false;
						showRewardSpin();
					}
				}
			}
		});
	}
	private float getAngle(){
		Random random=new Random();
		return random.nextInt(20)+CommonUtil.getAngle(reward)-random.nextInt(20);
	}
	
	REWARDs reward=REWARDs.PHONE_CARD;
	int rewardImage=0;
	private float previousAngle=0.0f;
	long startTime=0;
	
	private float velocity=1500;
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EventBus.getDefault().register(this);
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		EventBus.getDefault().unregister(this);
	}
	public void onEventMainThread(OnGetViewSizeDoneEvent event){
		
	}
	
	private void rotateTheWheel(float degrees) {
		matrix.postRotate(degrees, circleWidth / 2, circleHeight / 2);
		float[] values=new float[9];matrix.getValues(values);
		Log.e("Matrix","Matrix: "+values[0]+","+values[1]+","+values[2]+","+values[3]+","+values[4]+","+values[5]+","+values[6]+","+values[7]+","+values[8]+",");
		myWheel.setImageMatrix(matrix);
	}
	float totalDegress=0;
	boolean disableConfirm=false;
	private void showConfirmSpin(){
		AlertDialog.Builder winDialog = new AlertDialog.Builder(
				this);
		LayoutInflater factory = LayoutInflater.from(this);
		final View view;
		view = factory.inflate(R.layout.confirm_spin, null);
		Button okBtn=(Button) view.findViewById(R.id.ok);
		okBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				if(disableConfirm){
					CommonUtil.disableShowConfirmSpin(SpinScreen.this);
				}
				spin();
			}
		});
		ImageView tym_type_img=(ImageView)view.findViewById(R.id.tym_type_img);
		CheckBox dontshowcheckboxAgain=(CheckBox) view.findViewById(R.id.dontshowcheckboxAgain);
		dontshowcheckboxAgain.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
				disableConfirm=isChecked;
				Log.e("disableConfirmSpin",disableConfirm+"");
			}
		});
		if(spinType!=0){
			tym_type_img.setImageResource(spinType);
		}
		Button cancelBtn=(Button) view.findViewById(R.id.cancel);
		cancelBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		winDialog.setView(view);
		dialog=winDialog.create();
		dialog.show();
//		dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
	}
	
	private void showRewardSpin(){
		AlertDialog.Builder winDialog = new AlertDialog.Builder(
				this);
		LayoutInflater factory = LayoutInflater.from(this);
		final View view;
		view = factory.inflate(R.layout.show_spin_reward, null);
		Button okBtn=(Button) view.findViewById(R.id.ok);
		okBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		ImageView reward_img=(ImageView)view.findViewById(R.id.reward_img);
		TextView numberOfReward=(TextView)view.findViewById(R.id.numberOfReward);
		TextView rewardLbl=(TextView)view.findViewById(R.id.line1);
		if(reward!=REWARDs.MISS&&spinType!=0){
			reward_img.setImageDrawable(getResources().getDrawable(rewardImage));
			numberOfReward.setText("23");
		}else{
			reward_img.setVisibility(View.INVISIBLE);
			numberOfReward.setText("");
			if(reward==REWARDs.TURN){
				rewardLbl.setText("Ban nhan duoc them 1 luot quay");
			}
			
		}
		winDialog.setView(view);
		dialog=winDialog.create();
		dialog.show();
	}
}